package com.qifei.xmlg_backend.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qifei.xmlg_backend.DTO.emp.EmpExcelDto;
import com.qifei.xmlg_backend.DTO.emp.EmpQueryParam;
import com.qifei.xmlg_backend.entity.Emp;
import com.qifei.xmlg_backend.entity.ErrorCode;
import com.qifei.xmlg_backend.entity.PageBean;
import com.qifei.xmlg_backend.exception.CustomException;
import com.qifei.xmlg_backend.mapper.EmpMapper;
import com.qifei.xmlg_backend.service.IEmpService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import static jakarta.xml.bind.DatatypeConverter.parseDate;

/**
 * <p>
 * 员工表 服务实现类
 * </p>
 *
 * @author qifei
 * @since 2025-06-10
 */
@Service
@Slf4j
public class EmpServiceImpl extends ServiceImpl<EmpMapper, Emp> implements IEmpService {


    private final EmpMapper empMapper;

    public EmpServiceImpl(EmpMapper empMapper) {
        this.empMapper = empMapper;
    }

    @Override
    public PageBean<Emp> getEmpList(EmpQueryParam param) {
        System.out.println(param.getPage());
        Page<Emp> page = new Page<>(param.getPage(),param.getPageSize());
        List<Emp> emps = empMapper.selectPageVo(page, param.getName(), param.getGender(), param.getBegin(), param.getEnd());
        PageBean<Emp> pageBean = new PageBean<>(page.getTotal(),emps);
        return pageBean;
    }

    @Override
    public void importExcel(MultipartFile file) {
        try{
            List<EmpExcelDto> emplist = EasyExcel.read(file.getInputStream(),EmpExcelDto.class,null).charset(Charset.forName("GBK")).sheet().doReadSync();
            for (EmpExcelDto empdto : emplist) {
                log.info(String.valueOf(empdto));
                Emp emp = new Emp();
                emp.setId(empdto.getId());
                emp.setUsername(empdto.getUsername());
                emp.setName(empdto.getName());
                emp.setDeptId(empdto.getDeptId());


                if ("男".equals(empdto.getGender())) {
                    emp.setGender(1);
                } else if ("女".equals(empdto.getGender())) {
                    emp.setGender(2);
                } else {
                    emp.setGender(null);
                }

                if (empdto.getJob() != null) {
                    switch (empdto.getJob()) {
                        case "班主任": emp.setJob(1); break;
                        case "讲师": emp.setJob(2); break;
                        case "学工主管": emp.setJob(3); break;
                        case "教研主管": emp.setJob(4); break;
                    }
                }else{
                    emp.setJob(null);
                }


                if (empdto.getEntrydate() != null && !empdto.getEntrydate().isEmpty()) {
                    emp.setEntrydate(parseDate(empdto.getEntrydate()));
                }

                emp.setUpdateTime(LocalDateTime.now());

                if (emp.getId() != null && empMapper.selectById(emp.getId()) != null) {
                    this.updateById(emp);
                } else {
                    this.save(emp);
                }
            }

        }catch (Exception e){
            log.error(e.getMessage());
            throw new CustomException(ErrorCode.SERVER_ERROR);
        }
    }
    private LocalDate parseDate(String dateStr) {
        DateTimeFormatter[] patterns = {
                DateTimeFormatter.ofPattern("yyyy/MM/dd"),
                DateTimeFormatter.ofPattern("yyyy-M-d"),
                DateTimeFormatter.ofPattern("yyyy-MM-dd")
        };

        for (DateTimeFormatter pattern : patterns) {
            try {
                return LocalDate.parse(dateStr, pattern);
            } catch (Exception ignored) { }
        }
        throw new RuntimeException("无法解析日期: " + dateStr);
    }

    @Override
    public void exportSelected(List<Integer> ids, HttpServletResponse response) {
        List<Emp> selectedEmps = empMapper.selectBatchIds(ids);

        // 可选：把 Emp 映射成 DTO（列头更友好）
        List<EmpExcelDto> exportList = selectedEmps.stream().map(emp -> {
            EmpExcelDto dto = new EmpExcelDto();
            dto.setId(emp.getId());
            dto.setUsername(emp.getUsername());
            dto.setName(emp.getName());
            dto.setGender(emp.getGender() == 1 ? "男" : emp.getGender() == 2 ? "女" : "");
            dto.setJob(jobName(emp.getJob()));
            dto.setEntrydate(emp.getEntrydate() != null ? emp.getEntrydate().toString() : "");
            dto.setDeptId(emp.getDeptId());
            return dto;
        }).toList();

        // 设置响应头：中文文件名要 URL 编码
        String fileName = URLEncoder.encode("员工信息.xlsx", StandardCharsets.UTF_8);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + fileName);

        try {
            EasyExcel.write(response.getOutputStream(), EmpExcelDto.class)
                    .sheet("员工信息")
                    .doWrite(exportList);
        }catch (Exception e){
            log.error(e.getMessage());
            throw new CustomException(ErrorCode.SERVER_ERROR);
        }

    }

    private String jobName(Integer job) {
        if (job == null) return "";
        return switch (job) {
            case 1 -> "班主任";
            case 2 -> "讲师";
            case 3 -> "学工主管";
            case 4 -> "教研主管";
            default -> "";
        };
    }

}
